package me.out1kiss.www.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class MyUtil {

    private static final List<String> dataa = new ArrayList<>();
    private static final Logger LOGGER = LoggerFactory.getLogger(MyUtil.class);

    public static List<String> getData(String dir) {
        if (dataa.isEmpty()) {
            try {
                exportCsv(dir);
            } catch (IOException e) {
            }
        }
        return dataa.stream().distinct().collect(Collectors.toList());
    }

    public static String enRegex(String str) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            sb.append(str.charAt(i));
            sb.append(".*");
        }
        return ".*" + sb;
    }

    public static void exportCsv(String dir) throws IOException {
        Path root = Paths.get(dir);
        Files.walkFileTree(root, new SimpleFileVisitor<>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                String filename = file.getFileName().toString();
                if (filename.endsWith("xls") || filename.endsWith("xlsx") || filename.endsWith("csv")) {
                    PageReadListener<Object> objectPageReadListener = new PageReadListener<>(data -> {
                        List<Map> maps = JsonUtil.objToList(data, Map.class);
                        for (Map map : maps) {
                            String string = map.values().stream()
                                    .map(str -> str == null ? "" : str.toString().trim()).collect(Collectors.joining(",")).toString();
                            dataa.add(string);
                        }
                    });
                    try {
                        EasyExcel.read(file.toFile(), objectPageReadListener).sheet().doRead();
                        LOGGER.info("read file:{}", filename);
                    } catch (Exception e) {
                        LOGGER.warn("not read file:{}", filename);
                    }
                }
                return super.visitFile(file, attrs);
            }

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                return super.preVisitDirectory(dir, attrs);
            }
        });
    }
}
